package box.interview.wx.miniapp.controller;

import box.interview.wx.miniapp.config.ApplicationConfig;
import box.interview.wx.miniapp.controller.vo.WxMiniappCategoryVO;
import box.interview.wx.miniapp.controller.vo.WxMiniappInterviewVO;
import box.interview.wx.miniapp.entity.WxMiniappCategory;
import box.interview.wx.miniapp.entity.WxMiniappInterview;
import box.interview.wx.miniapp.mapper.WxMiniappCategoryMapper;
import box.interview.wx.miniapp.mapper.WxMiniappInterviewMapper;
import box.interview.wx.miniapp.service.ICollectRankingService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/com/wx/data")
public class DataController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private ICollectRankingService collectRankingService;

    @Autowired
    private WxMiniappInterviewMapper wxMiniappInterviewMapper;

    @Autowired
    private WxMiniappCategoryMapper wxMiniappCategoryMapper;

    @GetMapping("homeData")
    public ResponseEntity getHomeData() {
        Map<String, Object> result = new HashMap<>();
        // 查询金刚区
        QueryWrapper<WxMiniappCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        List<WxMiniappCategory> list = wxMiniappCategoryMapper.selectList(wrapper);
        result.put("navList", list);

        Map<Long, Long> cateCountMap = new HashMap<>();
        QueryWrapper<WxMiniappInterview> wrapper0 = new QueryWrapper<>();
        wrapper0.select("cate_id,count(id) as count");
        wrapper0.groupBy("cate_id");
        List<Map<String, Object>> list0 = wxMiniappInterviewMapper.selectMaps(wrapper0);
        if (list0 != null) {
            for (Map<String, Object> item : list0) {
                Long cateId = (Long) item.get("cate_id");
                Long count = (Long) item.get("count");
                cateCountMap.put(cateId, count);
            }
        }

        // 查询分类列表
        List<WxMiniappCategoryVO> cateList = new ArrayList<>();
        QueryWrapper<WxMiniappCategory> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("status", 1);
        wrapper2.eq("level", 1);
        List<WxMiniappCategory> list2 = wxMiniappCategoryMapper.selectList(wrapper2);
        if (list2 != null && list2.size() > 0) {
            for (WxMiniappCategory item : list2) {
                WxMiniappCategoryVO vo = new WxMiniappCategoryVO();
                vo.setId(item.getId());
                vo.setName(item.getName());
                vo.setImgUrl(item.getImgUrl());
                vo.setPid(item.getPid());
                vo.setLevel(item.getLevel());
                vo.setStatus(item.getStatus());
                vo.setCreateDate(item.getCreateDate());
                vo.setUpdateDate(item.getUpdateDate());
                QueryWrapper<WxMiniappCategory> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("pid", item.getId());
                List<WxMiniappCategory> childs = wxMiniappCategoryMapper.selectList(wrapper3);
                List<WxMiniappCategoryVO> childvos = new ArrayList<>();
                if (childs != null) {
                    for (WxMiniappCategory ii : childs) {
                        WxMiniappCategoryVO childvo = new WxMiniappCategoryVO();
                        childvo.setId(ii.getId());
                        childvo.setName(ii.getName());
                        childvo.setImgUrl(ii.getImgUrl());
                        childvo.setPid(ii.getPid());
                        childvo.setLevel(ii.getLevel());
                        childvo.setStatus(ii.getStatus());
                        childvo.setCreateDate(ii.getCreateDate());
                        childvo.setUpdateDate(ii.getUpdateDate());
                        Long count = cateCountMap.get(ii.getId());
                        count = count == null ? 0 : count;
                        childvo.setCount(count);
                        childvos.add(childvo);
                    }
                }
                vo.setChilds(childvos);
                cateList.add(vo);
            }
        }
        result.put("cateList", cateList);

        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @GetMapping("getDataDetail")
    public ResponseEntity getDataDetail(HttpServletRequest request, Long id) {
        WxMiniappInterview item = wxMiniappInterviewMapper.selectById(id);

        WxMiniappInterviewVO vo = new WxMiniappInterviewVO();
        vo.setId(item.getId());
        vo.setTitle(item.getTitle());
        vo.setContent(item.getContent());
        vo.setCateId(item.getCateId());
        vo.setStatus(item.getStatus());
        vo.setCreateDate(item.getCreateDate());
        vo.setUpdateDate(item.getUpdateDate());
        WxMiniappCategory cate = wxMiniappCategoryMapper.selectById(item.getCateId());
        vo.setCatename(cate.getName());

        // 未收藏
        Integer collect = 0;

        // 查询题目是否被收藏
        String token = request.getHeader("token");
        if (token != null && token.length() > 0) {
            // token -> openid
            String skey2openid = applicationConfig.skey2openid;
            // openid -> interview
            String openid2interviewId = applicationConfig.openid2interviewId;
            // token -> openid
            Object obj = redisTemplate.opsForHash().get(skey2openid, token);
            if (obj != null) {
                String openid = (String) obj;
                // openid -> interview
                Object collectObj = redisTemplate.opsForHash().get(openid2interviewId, openid);
                if (collectObj != null) {
                    // 有收藏
                    Map<Long, Long> collectMap = JSON.parseObject(collectObj.toString(), new TypeReference<Map<Long, Long>>() {
                    });
                    if (collectMap != null && collectMap.containsKey(item.getId())) {
                        collect = 1;
                    }
                }
            } else {
                // 重新登录
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
        }
        vo.setCollect(collect);
        return ResponseEntity.status(HttpStatus.OK).body(vo);
    }

    @GetMapping("getDataListByCate")
    public ResponseEntity getDataListByCate(Integer cateId, Integer page, Integer pageSize) {
        WxMiniappCategory wxMiniappCategory = wxMiniappCategoryMapper.selectById(cateId);
        if (wxMiniappCategory != null) {
            String name = wxMiniappCategory.getName();
            if ("收藏榜单".equals(name)) {
                List<WxMiniappInterview> list = collectRankingService.getDataCollectRanking(pageSize);
                return ResponseEntity.status(HttpStatus.OK).body(list);
            }
        }

        QueryWrapper<WxMiniappInterview> wrapper = new QueryWrapper<>();
        wrapper.eq("cate_id", cateId);
        List<WxMiniappInterview> list = wxMiniappInterviewMapper.selectList(wrapper);

        return ResponseEntity.status(HttpStatus.OK).body(list);
    }

    @GetMapping("getDataSearch")
    public ResponseEntity getDataSearch(String query, Integer page, Integer pageSize) {
        QueryWrapper<WxMiniappInterview> wrapper = new QueryWrapper<>();
        wrapper.like("title", query).or().like("content", query);
        List<WxMiniappInterview> list = wxMiniappInterviewMapper.selectList(wrapper);
        return ResponseEntity.status(HttpStatus.OK).body(list);

    }

}
